import axios from "axios";
import { ElMessage } from "element-plus";
import { getToken } from "@/utils/token";
var request = axios.create({
  baseURL: process.env.VUE_APP_URL || "",
});
request.interceptors.request.use(
  (config) => {
    config.headers["authorization"] = getToken();
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);
request.interceptors.response.use(
  (data) => {
    if (data.data.code == 500) {
      ElMessage.error(data.data.msg);
    }
    return data.data;
  },
  (err) => {
    return Promise.reject(err);
  }
);
/**
 *
 * @param {传url} url
 * @param {返回回调} callback
 * @returns 这里返回的是wsObj你可能不理解为什么要返回对象呢
 * 解释：如果你直接返回ws实例不算是对象所以用的时候就是浅拷贝
 *      你会发现你重连的时候根本获取不到最新的ws所以这里你要加一层对象这样当重连的时候改变指针即可
 */
request.ws = function (url, callback) {
  var time = null;
  var count = 0;
  var maxCount = 10; //最大链接次数
  var whiteCode = [1005, 1000]; //状态为多少时不用重连
  var onceTime = 2000; //多久尝试一次重连
  var heartbeat = {
    //心跳信息
    time: null,
    msg: "heartbeat",
    onceTime: 1000 * 60,
  };
  let wsObj = {
    ws: null,
  };
  var VUE_APP_URL = process.env.VUE_APP_URL || window.location.origin;
  var wsUrl = VUE_APP_URL.replace(/^(http|https)/, "ws") + "/ws" + url;
  websocketConnect();
  /**
   * 关闭链接的时候清除心跳
   */
  function clearHeartBeat() {
    if (heartbeat.time) {
      clearInterval(heartbeat.time);
      heartbeat.time = null;
    }
  }
  function websocketConnect() {
    wsObj.ws = new WebSocket(wsUrl);
    wsObj.ws.onerror = (err) => {
      callback && callback(err);
    };
    wsObj.ws.onopen = () => {
      count = 0;
      heartbeat.time = setInterval(() => {
        //心跳
        wsObj.ws.send(heartbeat.msg);
      }, heartbeat.onceTime);
      callback && callback(null, wsObj);
    };
    wsObj.ws.onclose = (e) => {
      clearHeartBeat();
      if (!whiteCode.includes(e.code) && !time && count < maxCount) {
        time = setTimeout(() => {
          websocketConnect();
          count++;
          time = null;
        }, onceTime);
      }
    };
  }
  return wsObj;
};
export default request;
